const { getErr } = require('../routes/getSendResult')
const { pathToRegexp } = require('path-to-regexp')
const jwt = require('../routes/jwt')
const needTokenApi = [
  // { method: 'POST', path: '/api/article/(.*)' },
  { method: 'POST', path: '/api/article/create' },
  { method: 'DELETE', path: '/api/article/:articleId' },
  { method: 'PUT', path: '/api/article/:articleId' },
  { method: 'POST', path: '/api/admin' },
  { method: 'DELETE', path: '/api/admin/:adminId' }
]

// 用于解析token
module.exports = (req, res, next) => {
  const apis = needTokenApi.filter((api) => {
    const reg = pathToRegexp(api.path)
    return api.method === req.method && reg.exec(req.path)
  })

  // 该路径不用权限
  if (apis.length === 0) {
    next()
    return
  }
  // 这里是需要权限的
  const result = jwt.verify(req)
  if (result) {
    //认证通过
    // req.adminId = result.id
    next()
  } else {
    //认证失败
    handleNonToken(req, res, next)
  }
}

//处理没有认证的情况
function handleNonToken(req, res) {
  res.status(403).send(getErr('you dont have any token to access the api', 403))
}
